/**
 * 战绩
 * Created by duwei on 2018/6/4.
 */
var RecordWindow = Window.extend({
    _ccsFileName: res.RecordWindow_json,
    _itemWidth:996,
    _itemHeight:151,
    _itemaddHeight:50,
    tabBtnTpyes: {
        majiang: 0,
        poker: 1,
        kaokao: 2
    },
    tabBtnMaps:{
        //0: [app.map_id.ZHUANZHUAN,app.map_id.CHANGSHA,app.map_id.HONGZHONG,app.map_id.PDK,app.map_id.JDDDZ,app.map_id.LZDDZ],//麻将
        0: [app.map_id.WD,app.map_id.QYLDS,app.map_id.YZCHZ]
        // 1: [app.map_id.PDK],//扑克
        // 2: [app.map_id.HUAIHUA_HONGGUAIWAN]//考考
    },
    /**
     * 监听触摸
     * @private
     */
    _initClickListeners: function () {
        this._super();
        this._clickListeners = {
            'btn_playback': '_clickPlayback'
        };
    },
    /**
     * 查看回放
     * @private
     */
    _clickPlayback: function () {
        showWindow('RecordPlayBackWindow');
    },
    /**
     * 初始化界面
     * @private
     */
    initWindow: function () {
        var self = this;
        this._initTabBtnsNode();
    },
    /**
     * 初始化页签
     */
    _initTabBtnsNode: function () {
        var self = this;
        self._listBtnScroll = self._nodeList["_listBtnScroll"];
        self._listBtnScroll.getParent().setLocalZOrder(10);
        self._tabBtnsNode = self._nodeList["_tabBtnsNode"];
        self._dataScroll = self._nodeList["_dataScroll"];
        self._touchNode = self._nodeList["_touchNode"];
        self._touchNode.setVisible(false);

        self.allBtnsNode = {};
        self.allBtnsHeight = {};
        self.mapIdMap = hall.wanfaBtn;

        if(self._tabBtnsNode){
            //切换页签
            for (var i = 0; i < self._tabBtnsNode.getChildrenCount(); i++) {
                (function (i) {
                    var btn_tab = self._tabBtnsNode["btn_tab" + i];
                    btn_tab.setTag(i);
                    if (btn_tab) {
                        TouchUtil.setOnclickListener(btn_tab, function () {
                            self._refreshTabBtn(i);
                        });
                    }
                })(i)
            }
        }
        self._setDefaultTabBtn();
    },
    /**
     * 设置默认点击
     * @private
     */
    _setDefaultTabBtn: function () {
        var self = this;
        self._refreshTabBtn(0);
        //self._refreshTabBtn(self.tabBtnType || (cc.sys.localStorage.getItem("tabBtnType") || 0));
    },
    /**
     * 刷新页签
     * @param type
     */
    _refreshTabBtn: function (type) {
        var self = this;
        if (self.tabBtnType == type)
            return;
        if(self._tabBtnsNode){
            for (var i = 0; i < self._tabBtnsNode.getChildrenCount(); i++) {
                (function (i) {
                    var btn_tab = self._tabBtnsNode["btn_tab" + i];
                    btn_tab["Image_1"].setVisible(btn_tab.getTag() == type);
                })(i)
            }
        }
        // 玩法按钮列表
        self.mapIds = [];
        self.tabBtnType = type;
        self._setMapIds();
        self.refreshBtnMap();
        cc.sys.localStorage.setItem("tabBtnType",type);
    },
    /**
     * 设置MapIds
     * @private
     */
    _setMapIds: function () {
        var self = this;
        self.mapIds = [];
        var mapIds = self.tabBtnMaps[self.tabBtnType];
        for (var i = 0; i < mapIds.length; i++) {
            var key = findKey(app.map_id, mapIds[i]);
            if(self.mapIdMap[key]){
                self.mapIds.push(mapIds[i]);
            }
        }
    },
    /**
     * 刷新按钮列表
     */
    refreshBtnMap: function () {
        var self = this;
        for (var key in self.allBtnsNode) {
            (function (key) {
                self.allBtnsNode[key].setVisible(key == self.tabBtnType);
            })(key);
        }
        if (!self.allBtnsNode[self.tabBtnType]) {
            self.allBtnsNode[self.tabBtnType] = duplicateNode(self._nodeList["_listBtnNode"]);
            self._listBtnScroll.addChild(self.allBtnsNode[self.tabBtnType]);
            var interval = (self._touchNode.getContentSize().height + 5);
            for (var i = 0; i < self.mapIds.length; i++) {
                (function (i) {
                    var button = self.allBtnsNode[self.tabBtnType]["touch" + i];
                    var key = findKey(app.map_id, self.mapIds[i]);
                    if (!button) {
                        button = duplicateNode(self._touchNode);
                        button.setName("touch" + i);
                        button.setPositionY(self._touchNode.getPositionY() - interval * i);
                        button.getChildByName('unselect').getChildByName('word').setTexture(self.mapIdMap[key].btn_normal);
                        button.getChildByName('select').getChildByName('word').setTexture(self.mapIdMap[key].btn_foucs);
                        button.setVisible(true);
                        self.allBtnsNode[self.tabBtnType].addChild(button);
                        self.allBtnsNode[self.tabBtnType]["touch" + i] = button;
                    }
                    var data = {};
                    data.mapkey = key;
                    button.setUserData(data);
                    TouchUtil.setOnclickListener(button, function () {
                        self.refreshButton(data.mapkey);
                    }, {swallowTouches: false});
                })(i);
            }
            self.allBtnsHeight[self.tabBtnType] = interval * self.mapIds.length;
        }

        var width = self._listBtnScroll.getContentSize().width;
        var height = self.allBtnsHeight[self.tabBtnType] > self._listBtnScroll.getContentSize().height ? self.allBtnsHeight[self.tabBtnType] : self._listBtnScroll.getContentSize().height;
        self._listBtnScroll.setInnerContainerSize(cc.size(width, height));
        self.allBtnsNode[self.tabBtnType].setPositionY(height);

        self._setDefaultButton();
    },
    /**
     * 设置默认玩法
     * @private
     */
    _setDefaultButton: function () {
        var self = this;
        var btnIndex = cc.sys.localStorage.getItem(self.tabBtnType + "_" + 'RecordBtnIndex') || 0;
        self.refreshButton(findKey(app.map_id, self.mapIds[btnIndex]));
        self._listBtnScroll.scrollToPercentVertical(100 / self.mapIds.length * btnIndex, 0.01, false);
    },
    /**
     * 刷新玩法按钮
     * @param mapkey
     */
    refreshButton: function (mapkey) {
        var self = this;
        for (var i = 0; i < self.mapIds.length; i++) {
            (function (i) {
                var button = self.allBtnsNode[self.tabBtnType]["touch" + i];
                var data = button.getUserData();
                button.getChildByName('unselect').setVisible(data.mapkey != mapkey);
                button.getChildByName('select').setVisible(data.mapkey == mapkey);
                if (data.mapkey === mapkey)
                    self._setChoiceButton(i);
            })(i);
        }
        self.mapkey = mapkey;
        showLoading('加载战绩中...');
        self.createContent();
        self.refreshDataScroll();
    },
    /**
     * 记录选择按钮
     * @param index
     * @private
     */
    _setChoiceButton: function (index) {
        var self = this;
        cc.sys.localStorage.setItem(self.tabBtnType + "_" + 'RecordBtnIndex', index);
    },
    /**
     * 创建列表
     */
    createContent: function () {
        var self = this;
        if (self.tableView) {
            self.tableView.removeFromParent();
            self.tableView = null;
            self.itemList = [];
        }
        var tableView = new cc.TableView(self, cc.size(self._dataScroll.getContentSize().width, self._dataScroll.getContentSize().height));
        tableView.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
        tableView.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);
        tableView.x = 0;
        tableView.y = 0;
        tableView.setDelegate(this);
        tableView.setBounceable(true);
        self._dataScroll.getParent().addChild(tableView);
        tableView.setPosition(self._dataScroll.getPosition());
        self._dataScroll.setVisible(false);
        self.tableView = tableView;
    },
    tableCellTouched: function (table, cell) {
        var self = this;
        var data = self.itemList[cell.getIdx()];
        showWindow('RecordDetailWindow', data);
        // if(data.map_id == 4000) {
        //     PopupLayerControlier.showLayer(new RecordBrieflyLayer(self.data));
        // }else{
        //     PopupLayerControlier.showLayer(new RecordDetailLayer(data));
        //}
    },
    tableCellSizeForIndex: function (table, idx) {
        var self = this;
        var itemdata = self.itemList[idx];
        var length = 0;
        for (var k = 1; k <= 6; k++) {
            if (itemdata["uid" + k]) {
                length++;
            }
        }
        var row = length > 0 ? Math.floor((length - 1) / 4) : 0;
        return cc.size(self._itemWidth, self._itemHeight + row * self._itemaddHeight);
    },
    tableCellAtIndex: function (table, idx) {
        var self = this;
        var cell = table.dequeueCell();
        var node = null;
        if (cell == null) {
            cell = new cc.TableViewCell();
            node = addItem('RecordCellItem',cell,idx,self.itemList[idx]);
            node.setName("itemCell");
        } else {
            node = cell.getChildByName("itemCell");
            node.setData(idx, self.itemList[idx]);
        }
        return cell;
    },
    numberOfCellsInTableView: function () {
        if (this.itemList == null) return 0;
        return this.itemList.length;
    },
    /**
     * 解析数据
     * @param data
     * @private
     */
    _parseData: function (data) {
        var self = this;
        hideLoading();
        var dataJson = JSON.parse(data);
        if (dataJson.result != 0) {
            showAlert('战绩解析失败!请重试.');
        }
        if (dataJson != null && dataJson.result == 0) {
            self.itemList = dataJson.data;
            if (self.itemList) {
                var nozhanji = self._nodeList["_nozhanji"];
                nozhanji.setVisible(self.itemList.length == 0);
            }
            self.itemList.sort(function (a, b) {
                return b['create_time'] - a['create_time'];
            });
            var Height = 0;
            var isoDate = timestamp2time(getCurTimestamp(), "isoDate");
            var num = 0;
            for (var i = 0; i < self.itemList.length; i++) {
                var itemdata = self.itemList[i];
                var length = 0;
                var isExist = false;
                for (var k = 1; k <= 6; k++) {
                    if (itemdata["uid" + k]) {
                        if (itemdata["uid" + k] == gameData.uid) {
                            isExist = true;
                        }
                        length++;
                    }
                }
                var row = length > 0 ? Math.floor((length - 1) / 4) : 0;
                Height += row * self._itemaddHeight;
                var cum = timestamp2time(itemdata['create_time'], "isoDate");
                if (cum == isoDate && isExist) {
                    num++;
                }
            }
            tableViewRefresh(self.tableView);
            self._nodeList["_num"].setString("今日总局数：（" + num + "局）");
            //移动到第一行
            var innerHeight = self.itemList.length * self._itemHeight + Height;
            self.tableView.setContentOffset(cc.p(0, (-innerHeight + self._dataScroll.getContentSize().height)), false);
        }
    },
    /**
     * 请求地址
     * @return {string}
     * @private
     */
    _getUrl: function () {
        var self = this;
        if (app.map_id[self.mapkey] == app.map_id.QYLDS || app.map_id[self.mapkey] == app.map_id.WD ||
            app.map_id[self.mapkey] == app.map_id.YZCHZ) {
            var request = app.recordPath[3] +'/Record?UserID=' + gameData.uid + '&mapid=' + app.map_id[self.mapkey];
            return request;
        }else {
            var request = '/Record/' + app.recordPath[0] + '?UserID=' + gameData.uid + '&mapid=' + app.map_id[self.mapkey];
            var sign = CryptoJS.MD5("request:" + request);
            return app.recordPath[3] + request + '&sign=' + sign;
        }
    },
    /**
     * 刷新数据列表
     * @param retryCnt
     */
    refreshDataScroll: function (retryCnt) {
        var self = this;
        // cc.log(self._getUrl());
        http.get(self._getUrl(), this._parseData.bind(this), function () {
            retryCnt = typeof retryCnt == 'undefined' ? 0 : retryCnt;
            if (retryCnt < 3) {
                retryCnt++;
                self.refreshDataScroll(retryCnt);
                showAlert("正在进行第" + parseInt(retryCnt) + "次重试");
            } else {
                showAlert('请求信息失败,请检查您的网络');
            }
        });
    }
});